package com.itheima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.behaviour.dto.FollowBehaviorDto;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.user.mapper.ApUserFanMapper;
import com.itheima.user.mapper.ApUserFollowMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUserFan;
import com.itheima.user.pojo.ApUserFollow;
import com.itheima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dto.UserRelationDto;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>APP用户信息 业务实现</p>
 * @package com.itheima.user.service.impl
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Override
    public Map<String, Object> loginCheck(Map<String, String> map) {
        String phone = map.get("phone");
        String password = map.get("password");
        String equipmentId = map.get("equipmentId");
        Map<String, Object> result = new HashMap<>();
        //2. 参数非空校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            if (equipmentId.equals("88888888")) {
                //如果phone和password  那么就为匿名用户
                String token = AppJwtUtil.createToken(SystemConstants.ANONYMOUS_USER_ID);
                result.put("token", token);
                return result;
            }
            throw new LeadNewsException("用户名或密码错误!");
        }
        //根据phone查询
        ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
        if (apUser == null) {
            throw new LeadNewsException("用户名或密码错误!");
        }

        String encryptedPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
        if (!apUser.getPassword().equals(encryptedPwd)) {
            throw new LeadNewsException("用户名或密码错误!");
        }
        String token = AppJwtUtil.createToken(apUser.getId().longValue());

        result.put("token", token);
        result.put("apUser", apUser);

        return result;
    }

    /**
     * 用户关注与取消关注
     *
     * @param dto
     */
    @Override
    @Transactional
    public void userFollow(UserRelationDto dto) {
        //获取当前用户id
        Integer userId = Integer.parseInt(RequestContextUtil.getUserId());
        //判断是否为匿名登录
        if (RequestContextUtil.isAnonymous()) {
            //是匿名登录,需要登录后操作
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }
        Integer operation = dto.getOperation();
        Integer authorId = dto.getAuthorId();
        //判断是否是关注还是取消关注
        if (operation == 1) {
            //关注
            //判断根据用户id查询是否已经关注过
            LambdaQueryWrapper<ApUserFollow> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ApUserFollow::getUserId,userId);
            ApUserFollow apUserFollow = apUserFollowMapper.selectOne(lqw);
            if (null!=apUserFollow){
                throw new LeadNewsException("已关注");
            }
            //根据用户查询id
            ApUser apUser = getById(userId);
            //因为文章作者id同时也是用户iD,所以查询的名称也是一致
            ApUser author = getById(authorId);
            //添加关注
            addFollow(userId,author);
            //添加粉丝
            addFan(authorId,apUser);

            //关注行为编写
            //构建用户行为dto
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setFollowId(authorId);
            followBehaviorDto.setArticleId(dto.getArticleId());
            //关注者id
            followBehaviorDto.setUserId(userId);
            //发送消息到行为微服务
            kafkaTemplate.send(BusinessConstants.MqConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));
        }else {
            //取消关注
            //删除关注表
            removeFollow(userId,authorId);

            //删除粉丝表
            removeFans(authorId,userId);
            
        }
    }

    //添加粉丝
    private ApUserFan addFan(Integer authorId, ApUser apUser){
        //自己的账号添加粉丝
        //
        ApUserFan apUserFan = new ApUserFan();
        apUserFan.setId(null);
        //可以理解为  把  和  被,关注表是被我关注，粉丝表是自己成为粉丝  这里是以作者为主体
        //这里的用户是文章的作者id
        apUserFan.setUserId(authorId);
        //这是登录用户
        apUserFan.setFansId(apUser.getId());
        apUserFan.setFansName(apUser.getName());
        apUserFan.setLevel(0);
        apUserFan.setCreatedTime(LocalDateTime.now());
        apUserFan.setIsDisplay(1);
        apUserFan.setIsShieldComment(0);
        apUserFan.setIsShieldLetter(0);
        apUserFanMapper.insert(apUserFan);
        return apUserFan;
    }
    //添加关注
    private ApUserFollow addFollow(Integer userId,ApUser author) {
        //这里是以用户为主体
        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setId(null);
        //用户id
        apUserFollow.setUserId(userId);
        //关注的作者id
        apUserFollow.setFollowId(author.getId());
        //粉丝昵称即该文章作者名称
        apUserFollow.setFollowName(author.getName());
        apUserFollow.setLevel(1);// 一般
        apUserFollow.setIsNotice(1); // 要通知
        apUserFollow.setCreatedTime(LocalDateTime.now());
        apUserFollowMapper.insert(apUserFollow);
        return apUserFollow;
    }
    //删除关注
    private void removeFollow(Integer userId,Integer authorId){
        LambdaQueryWrapper<ApUserFollow> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApUserFollow::getUserId,userId);
        lqw.eq(ApUserFollow::getFollowId,authorId);
        apUserFollowMapper.delete(lqw);
    }

    //删除粉丝
    private void removeFans(Integer authorId,Integer userId){
        LambdaQueryWrapper<ApUserFan> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApUserFan::getUserId,authorId);
        lqw.eq(ApUserFan::getFansId,userId);
        apUserFanMapper.delete(lqw);
    }


//    public static 21void main(String[] args) {
//        String p = "adminadmin";
//        String encryptedPwd = DigestUtils.md5DigestAsHex(p.getBytes());
//        System.out.println("encryptedPwd = " + encryptedPwd);
//    }
}
